<template>
  <div id="dialogPubJob">
    <el-dialog
      class="about-set"
      title="添加我的作业"
      :visible.sync="dialogData.isShow"
      width="600px"
      top="20px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="选择学院" prop="collegeId">
            <el-select
              v-model="ruleForm.collegeId"
              filterable
              placeholder="选择学院"
              clearable
            >
              <el-option
                v-for="item in collegeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <showTagSelect
            ref="tagSelect"
            :channel="channel"
            @getTagIds="getTagIds"
          ></showTagSelect>
          <el-form-item label="选择马甲" filterable prop="userId">
            <el-select
              v-model="ruleForm.userId"
              filterable
              placeholder="请选择马甲"
              :disabled="ruleForm.canRobotRandom === true"
            >
              <el-option
                v-for="item in vestList"
                :key="item.robotId"
                :label="item.robotName"
                :value="item.robotId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="随机马甲">
            <el-switch
              v-model="ruleForm.canRobotRandom"
              :active-value="true"
              :inactive-value="false"
              active-color="#1DC8A4"
              @change="changeRandom(ruleForm.canRobotRandom)"
            ></el-switch>
          </el-form-item>
          <el-form-item label="选择课程" prop="xzkc">
            <el-select
              v-model="ruleForm.xzkc"
              filterable
              placeholder="请选择课程"
              clearable
            >
              <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择期" prop="jqzy">
            <el-select
              v-model="ruleForm.jqzy"
              filterable
              placeholder="请请选择期"
              clearable
            >
              <el-option
                v-for="item in stageList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="作业类型" prop="type">
            <el-radio-group v-model="ruleForm.type">
              <el-radio
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="ruleForm.taskId" label="">
            <el-button plain @click="showDetail">
              查看作业要求
            </el-button>
          </el-form-item>
          <el-form-item label="选择作业" prop="taskId">
            <el-select
              v-model="ruleForm.taskId"
              filterable
              placeholder="请选择章节列表"
              clearable
            >
              <el-option
                v-for="item in taskIdList"
                :key="item.taskId"
                :label="item.title"
                :value="item.taskId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="作业内容" prop="content">
            <el-input
              v-model="ruleForm.content"
              type="textarea"
              maxlength="60"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!--作业类型为图文-->
          <el-form-item
            v-show="ruleForm.type === 'TEXT'"
            label="添加作业"
            prop="imgInfo"
          >
            <uploadImg @setImgInfo="setImgInfo"></uploadImg>
          </el-form-item>
          <!--作业类型为小视频-->
          <el-form-item
            v-show="ruleForm.type === 'VIDEO'"
            label="添加作业"
            prop="vid"
          >
            <el-button id="upload" type="warning">
              上传视频
            </el-button>
            <span class="red-note">注：视频最长限制{{ maxSecond }}分钟</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
    <!--选择作业要求详细弹窗-->
    <jobDetail
      v-if="jobDetailData.isShow"
      :dialog-data="jobDetailData"
    ></jobDetail>
  </div>
</template>

<script>
import { courseList, stageList, taskIdList, pubJob } from '@/api/jobManagement' // 接口
import jobDetail from '@component/jobManagement/common/dialogDetail' // 作业要求详细弹窗
import uploadImg from '@common/uploadImg' // 上传图片公共组件
import showTagSelect from '@common/showTagSelect' // 显性标签下拉选择公共组件
import { getVideoPara } from '@utils/pubFunction'
import { uploadVideo } from '@utils/uploadVideo'
import {
  sysNormalDisable,
  getVestList,
  getRandomRobotId
} from '@utils/dictionariesFunc'
export default {
  name: 'DialogPubJob',
  msg: '作业管理-我的发布---发布作业',
  components: {
    jobDetail,
    uploadImg,
    showTagSelect
  },
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      collegeList: [{ dictValue: '', dictLabel: '- 请选择学院 -' }], // 学院
      vestList: [{ robotId: '', robotName: '- 请选择马甲 -' }], // 选择马甲
      courseList: [], // 选择课程
      stageList: [], // 选择期
      typeList: [], // 作业类型
      taskIdList: [], // 选择章节
      ruleForm: {
        collegeId: '', // 学院
        userId: '', // 马甲
        canRobotRandom: true, // 随机马甲 true/false
        xzkc: '', // 课程
        jqzy: '', // 期
        type: 'TEXT', // 作业类型 与作业任务一致 TEXT 图片|VIDEO 视频
        taskId: '', // 选择作业
        content: '', // 作业内容
        vid: '', // 视频vid
        imgInfo: '' // 图片
      },
      rules: {
        collegeId: [
          { required: true, message: '请选择学院' }
          /* {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'} */
        ],
        // userId: { required: true, message: '请选择马甲' },
        userId: {},
        jqzy: { required: true, message: '请选择期' },
        xzkc: [{ required: true, message: '请选择课程' }],
        type: { required: true, message: '请选择作业类型' },
        taskId: { required: true, message: '请选择作业任务' },
        content: {
          required: true,
          message: '作业内容不能为空',
          trigger: 'change'
        },
        imgInfo: { required: true, message: '请上传作业图片' },
        vid: {}
      },
      jobDetailData: {
        isShow: false, // 默认隐藏
        params: '', // 编辑时，传递的参数
        stageId: '' // 期id
      },
      polivNum: {
        polyvUserId: '',
        polyvSecretKey: '',
        polyvWriteToken: '',
        polyvReadToken: ''
      },
      upVideo: null,
      maxSecond: 3, //视频最长限制,试学课 1分钟;VIP课3分钟
      channel: 'JOB',
      labelItems: []
    }
  },
  watch: {
    'ruleForm.collegeId': {
      // 监听学院
      handler(newValue, oldValue) {
        // 学院改变后，清空课程列表+ 绑定课程
        this.ruleForm.xzkc = ''
        this.courseList = []
        if (newValue) {
          // 选择学院后，获取课程列表
          this.getCourseList(newValue)
        }
      },
      deep: true
    },
    'ruleForm.xzkc': {
      // 监听课程
      handler(newValue, oldValue) {
        // 课程改变后，清空期列表+ 绑定期，
        this.ruleForm.jqzy = ''
        this.stageList = []
        if (newValue) {
          // 选择课程后，获取期列表
          this.getStageList(newValue)
          //获取视频时限
          this.getMaxSecond(newValue)
        }
      },
      deep: true
    },
    'ruleForm.jqzy': {
      // 监听期
      handler(newValue, oldValue) {
        // 期改变后，清空选择章节列表+ 绑定章节，
        this.ruleForm.taskId = ''
        this.taskIdList = []
        if (newValue) {
          // 选择期后，获取章节列表
          this.getTaskIdList(newValue, this.ruleForm.type)
        }
      },
      deep: true
    },
    'ruleForm.canRobotRandom': {
      // 监听随机马甲
      handler(newValue, oldValue) {
        if (newValue === true) {
          // 随机马甲启用
          this.rules.userId = {}
        } else {
          // 随机马甲关闭
          this.rules.userId = { required: true, message: '请选择马甲' }
        }
      },
      deep: true
    },
    'ruleForm.type': {
      // 监听类型
      handler(newValue, oldValue) {
        let channel = ''
        if (newValue === 'VIDEO') {
          // 视频
          this.rules.imgInfo = {}
          this.rules.vid = { required: true, message: '请上传视频' }
          channel = 'SHORT_VIDEO'
        } else {
          // 图文
          this.rules.imgInfo = { required: true, message: '请上传作业图片' }
          this.rules.vid = {}
          channel = 'JOB'
        }
        // 期改变后，清空选择章节列表+ 绑定章节，
        this.ruleForm.taskId = ''
        this.taskIdList = []
        if (newValue && this.ruleForm.jqzy) {
          // 选择期后，获取章节列表
          this.getTaskIdList(this.ruleForm.jqzy, newValue)
        }
        this.labelItems = []
        this.$refs.tagSelect.clearTagIds()
        this.$refs.tagSelect.getTagList(channel)
      },
      deep: true
    }
  },
  computed: {
    dapengUserId() {
      return this.$store.state.user.dapengUserId
    }
  },
  mounted() {
    this.getStatusList()
    this.getPolivNum()
  },
  methods: {
    /* 获取系统配置-保利威视 */
    getPolivNum() {
      let _this = this
      getVideoPara().then((data) => {
        this.polivNum = { ...data }
        uploadVideo(_this.polivNum, _this.saveVideo).then((resObj) => {
          _this.upVideo = resObj
        })
      })
    },
    /* 获取数据状态 */
    async getStatusList() {
      // 作业类型
      this.typeList = await sysNormalDisable('sys_task_type')
      // 学院
      let data = await sysNormalDisable('sys_college')
      this.collegeList = this.collegeList.concat(data)
      // 马甲
      let data1 = await getVestList(this.dapengUserId)
      this.vestList = this.vestList.concat(data1)
    },
    /* 根据学院id,获取课程列表 */
    getCourseList(collegeId) {
      let obj = {
        collegeId
      }
      courseList(obj, (response) => {
        this.courseList = [{ id: '', title: '- 请选择课程 -' }, ...response]
      })
    },
    /* 根据课程id,获取获取期列表 */
    getStageList(courseId) {
      stageList(courseId, (response) => {
        this.stageList = [{ id: '', title: '- 请选择期 -' }, ...response]
      })
    },
    /* 根据期次id,获取作业任务列表 */
    getTaskIdList(stageId, jobType) {
      let obj = {
        stageId,
        jobType
      }
      taskIdList(stageId, obj, (response) => {
        this.taskIdList = [
          { taskId: '', title: '- 请选择章节列表 -' },
          ...response
        ]
      })
    },
    /*获取视频时限*/
    getMaxSecond(courseId) {
      let item = this.courseList.find((item) => item.id === courseId)
      this.maxSecond = item.type === 'VIP' ? 3 : 1
    },
    /* 显示作业要求弹窗 */
    showDetail() {
      this.jobDetailData.isShow = true
      this.jobDetailData.params = this.ruleForm.taskId
      this.jobDetailData.stageId = this.ruleForm.jqzy
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.upVideo.update({
        uploadSuccess: ''
      })
      clearInterval(this.upVideo.timer)
      this.upVideo.destroy()
      this.dialogData.isShow = false
    },
    /* 保存上传视频 */
    async saveVideo(fileData) {
      this.ruleForm.vid = fileData.vid
    },
    /* 图片上传成功后，获取返回结果 */
    setImgInfo(str) {
      this.ruleForm.imgInfo = str
    },
    /* 改变随机马甲按钮状态 */
    changeRandom(status) {
      if (status === true) {
        // 启用随机马甲
        if (this.vestList.length === 0) {
          this.$message({
            message: '马甲列表为空，无法选择随机马甲',
            type: 'error'
          })
          this.ruleForm.canRobotRandom = true
        }
      }
    },
    /*整合选择的标签*/
    setIabelInfos() {
      let ary = []
      this.labelItems.forEach((item, index) => {
        let { labelProperty: labelCategoryProperty, labelId, labelName } = item
        let obj = {
          labelCategoryProperty,
          labelId,
          labelName
        }
        ary.push(obj)
      })
      return [...ary]
    },
    /* 确认提交 */
    async confirmLabel(formName) {
      this.loading = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj = { ...this.ruleForm }
          delete obj.collegeId
          delete obj.xzkc
          delete obj.jqzy
          // userId,随机马甲时，取随机马甲，否则取当前马甲的robotId
          if (this.ruleForm.canRobotRandom === true) {
            obj.userId = (await getRandomRobotId(this.dapengUserId)) || ''
          }
          if (obj.type === 'VIDEO') {
            obj.imgInfo = []
          }
          //选中标签
          obj.labelInfos = this.setIabelInfos()
          pubJob(
            obj,
            (response) => {
              this.loading = false
              this.$emit('refresh')
              this.cancelLabel()
            },
            (response) => {
              this.loading = false
              this.$message.warning('发布作业失败，' + response.message)
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    /* 获取选中的显性标签 */
    getTagIds(items) {
      this.labelItems = [...items]
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less">
#dialogPubJob {
  @import url('~@common/style/textarea.less');
  .red-note {
    padding-left: 10px;
    color: #f00;
  }
  button.el-button.el-button--default.is-plain {
    width: 100%;
  }
  .el-form-item__error {
    padding: 0;
  }
  .el-dialog__wrapper {
    /*z-index: 3000 !important;*/
  }
}
</style>
